import api from '../../utils/api'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const app = getApp()
var WSCoordinate = require('../../utils/WSCoordinate.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {

    maskShow:false,
    mainActiveIndex: 0,
    activeId: null,
    currcity:'北京',
    status:'1',
    items:[],
    changepos:false,
    qrytype:1,

    imageBaseURL: app.imageBaseURL,
    imageResizeParams: app.imageResizeParams,

    latitude: 23.096994,
    longitude: 113.324520,
    markers: [],
    sourmarkers: [],
    markerids:[],
    scale:15
  },
  
  //地区选择点击
  onClickNav({ detail = {} }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
	app.globalData.firstAreaIndex = detail.index
  },
  onClickItem({ detail = {} }) {
    let _this = this
	console.log(detail)
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    let currcity = detail.text
	if( !activeId ){
		currcity = this.data.items[this.data.mainActiveIndex].text
	}
    this.setData({ activeId, maskShow:false, currcity, changepos:true });
  app.globalData.firstAreaId = activeId

  if( currcity ){
    app.globalData.BMap.geocoding({
      address: currcity,
      fail:function (res) {
        console.log(res)
      },
      success: function (res) {
        console.log(res)
        let wxMarkerData = res.wxMarkerData
        _this.setData({
          latitude: wxMarkerData[0].latitude,longitude: wxMarkerData[0].longitude
        })
      },
      iconPath: '/images/map/act16.png',
      iconTapPath: '/images/map/act16.png'
    });
  }
	  this.getData()
  },
  //区域显示/隐藏
  showRegion(){
	let _this = this
	console.log(_this.data.currcity)
	let mainActiveIndex = 0, activeId = null
	this.data.items.find(function(item,index) {
		console.log(item)
		if( _this.data.currcity.indexOf(item.text)>-1 ){
			mainActiveIndex = index
			activeId = null
			return true;
		}
		else{
			return item.children && item.children.find(function(item1,idx){
				if( _this.data.currcity.indexOf(item1.text)>-1 ){
					mainActiveIndex = index
					activeId = item1.id
					return true
				}else{
					return false
				}
			})
		}
	});
	console.log( mainActiveIndex,activeId)
		
    this.setData({ 
      maskShow:true, mainActiveIndex, activeId
     });
  },
  hideRegion(){
    this.setData({ 
      maskShow:false
     });
  },
  /* 阻止冒泡事件 */
  stopPropagation(){
    return;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let currpoint = app.globalData.currpoint
    let point = WSCoordinate.transformFromBaiduToGCJ(currpoint.latitude, currpoint.longitude);
    this.setData({
      latitude:point.latitude, 
      longitude:point.longitude,
      mainActiveIndex: app.globalData.firstAreaId,
      activeId:app.globalData.firstAreaId,
      currcity:app.globalData.address.city,
      items:app.globalData.addrList
    } )
    this.showRegion()
    this.setData({ maskShow:false });
    this.getData()
  },

  async getData () {
    let _this = this;
    const { scale } = this.data
    let data={}
    data['flag'] = 'map_list'
    data['location']={lat:this.data.latitude,lng:this.data.longitude}
    data['citycode'] =this.data.activeId?this.data.activeId:this.data.items[this.data.mainActiveIndex].id
    data['status'] = this.data.status
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      console.log(result)
      let list=[], markerids=[]
      if(result && result.club_list &&  result.club_list.length>0 ){
        let club_list = result.club_list.filter((item)=>{ 
          return (item.longitude!='' && item.latitude!='') && item.longitude!=NaN
        })
        club_list.forEach((item)=>{
          item['imgurl'] = api.checkurl(item['imgurl'])
          item['mtype'] = 1
          let youthtype = parseInt(item['youth_type'])
          if( youthtype==0){
            if( scale<=10 ) {
              item['itemtype']==1?item['iconPath'] = '/images/map/actIcon161.png':item['iconPath'] = '/images/map/txgwIcon161.png'
              item['width'] = "5px"
              item['height'] = "7px"
            }else if( scale<=12 ) {
              item['itemtype']==1?item['iconPath'] = '/images/map/actIcon241.png':item['iconPath'] = '/images/map/txgwIcon241.png'
              item['width'] = "13px"
              item['height'] = "15px"
            }else if( scale<=14 ) {
              item['itemtype']==1?item['iconPath'] = '/images/map/actIcon321.png':item['iconPath'] = '/images/map/txgwIcon321.png'
              item['width'] = "21px"
              item['height'] = "23px"
            }else if( scale<=16 ) {
              item['itemtype']==1?item['iconPath'] = '/images/map/actIcon401.png':item['iconPath'] = '/images/map/txgwIcon401.png'
              item['width'] = "29px"
              item['height'] = "31px"
            }else if( scale<=20 ) {
              item['itemtype']==1?item['iconPath'] = '/images/map/actIcon481.png':item['iconPath'] = '/images/map/txgwIcon481.png'
              item['width'] = "44px"
              item['height'] = "45px"
            }
          }else{
            let sname = 's';
            if( youthtype == 1 ) sname = 's';
            else if( youthtype == 4 ) sname = 'z';
            else sname = 'q';
            if( scale<=10 ) {
              item['iconPath'] = '/images/map/'+sname+'16.png'
              item['width'] = "5px"
              item['height'] = "7px"
            }else if( scale<=12 ) {
              item['iconPath'] = '/images/map/'+sname+'24.png'
              item['width'] = "13px"
              item['height'] = "15px"
            }else if( scale<=14 ) {
              item['iconPath'] = '/images/map/'+sname+'32.png'
              item['width'] = "21px"
              item['height'] = "23px"
            }else if( scale<=16 ) {
              item['iconPath'] = '/images/map/'+sname+'40.png'
              item['width'] = "29px"
              item['height'] = "31px"
            }else if( scale<=20 ) {
              item['iconPath'] = '/images/map/'+sname+'48.png'
              item['width'] = "44px"
              item['height'] = "45px"
            }
          }
          
          item['customCallout'] = {anchorY: 0, anchorX: 0, display: 'BYCLICK'}
          item['sysid'] = item['id']
          item['id'] = parseInt(api.RandNum(10))
          let point = WSCoordinate.transformFromBaiduToGCJ(item.latitude, item.longitude)
          item['latitude']=point.latitude
          item['longitude']=point.longitude
          markerids.push(item['id'])
        })
        list.push(...club_list)
      }
      if( result &&  result.act_list &&  result.act_list.length>0 ){
        let act_list = result.act_list.filter((item)=>{ 
          return (item.longitude!='' && item.latitude!='') && item.longitude!=NaN
        })
        act_list.forEach((item)=>{
          item['mtype'] = 2
          item['imgurl'] = api.checkurl(item['imgurl'])
          if( scale<=10 ) {
            item['iconPath'] = '/images/map/act16.png'
            item['width'] = "5px"
            item['height'] = "7px"
          }else if( scale<=12 ) {
            item['iconPath'] = '/images/map/act24.png'
            item['width'] = "13px"
            item['height'] = "15px"
          }else if( scale<=14 ) {
            item['iconPath'] = '/images/map/act32.png'
            item['width'] = "21px"
              item['height'] = "23px"
          }else if( scale<=16 ) {
            item['iconPath'] = '/images/map/act40.png'
            item['width'] = "29px"
            item['height'] = "31px"
          }else if( scale<=20 ) {
            item['iconPath'] = '/images/map/act48.png'
            item['width'] = "44px"
            item['height'] = "45px"
          }
          item['customCallout'] = {anchorY: 0, anchorX: 0, display: 'BYCLICK'}
          item['sysid'] = item['id']
          item['id'] = parseInt(api.RandNum(10))
          let point = WSCoordinate.transformFromBaiduToGCJ(item.latitude, item.longitude)
          item['latitude']=point.latitude
          item['longitude']=point.longitude
          markerids.push(item['id'])
        })
        list.push(...act_list)
      }
      //this.mapCtx.removeMarkers({markerIds:this.data.markerids,success:function//(){
        _this.setData({
          sourmarkers:list,markerids
        })
        console.log(list)
        if( list.length>0 && _this.data.changepos){
          _this.setData({
            /*latitude:list[0].latitude,longitude:list[0].longitude, */changepos:false
          })
        }
      //}})
      this.mapCtx.getRegion({success:function(res){
        let sourmarkers = _this.data.sourmarkers
        let bssw = res.southwest;   //可视区域左下角
        let bsne = res.northeast;   //可视区域右上角
        let topLat = bsne.latitude;
        let bottomLat = bssw.latitude;
        let leftLng = bssw.longitude;
        let rightLng = bsne.longitude;
        let markers = sourmarkers.filter((item)=>{ 
          if( _this.data.qrytype== 1){
          return (item.longitude < rightLng && item.longitude >leftLng)&&(item.latitude < topLat && item.latitude >bottomLat)
          }else if( _this.data.qrytype== 2){
            return (item.longitude < rightLng && item.longitude >leftLng)&&(item.latitude < topLat && item.latitude >bottomLat)  && item.mtype==2
          }else{
            return (item.longitude < rightLng && item.longitude >leftLng)&&(item.latitude < topLat && item.latitude >bottomLat)  && item.mtype==1
          }
        })
        console.log(markers)
        /*if( markers.length>50 ){
          markers.splice(50,markers.length)
        }*/
        _this.setData({markers})
      }})

    }else {
      Toast(message)
    }
  },

  clickact(){
    let _this = this
    this.mapCtx.getRegion({success:function(res){
      let qrytype = _this.data.qrytype
      qrytype==2?qrytype=1:qrytype=2
      let sourmarkers = _this.data.sourmarkers
      let bssw = res.southwest;   //可视区域左下角
      let bsne = res.northeast;   //可视区域右上角
      let topLat = bsne.latitude;
      let bottomLat = bssw.latitude;
      let leftLng = bssw.longitude;
      let rightLng = bsne.longitude;
      let markers = sourmarkers.filter((item)=>{ 
        return (item.longitude < rightLng && item.longitude >leftLng)&&(item.latitude < topLat && item.latitude >bottomLat) && (item.mtype==2 || qrytype==1)
      })
      console.log(markers)
      _this.setData({markers,qrytype})
    }})
  },

  clickorg(){
    let _this = this
    this.mapCtx.getRegion({success:function(res){
      let qrytype = _this.data.qrytype
      qrytype==3?qrytype=1:qrytype=3
      let sourmarkers = _this.data.sourmarkers
      let bssw = res.southwest;   //可视区域左下角
      let bsne = res.northeast;   //可视区域右上角
      let topLat = bsne.latitude;
      let bottomLat = bssw.latitude;
      let leftLng = bssw.longitude;
      let rightLng = bsne.longitude;
      let markers = sourmarkers.filter((item)=>{ 
        return (item.longitude < rightLng && item.longitude >leftLng)&&(item.latitude < topLat && item.latitude >bottomLat) && (item.mtype==1||qrytype==1)
      })
      console.log(markers)
      
      _this.setData({markers,qrytype})
    }})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let _this = this
    this.mapCtx = wx.createMapContext('myMap')
    this.mapCtx.getScale({success:function(res){
      _this.setData({scale:res.scale})
    }})
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getUser()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  markertap(e) {
    //console.log('@@@ markertap', e)
  },
  callouttap(e) {
    console.log('@@@ callouttap', e)
    let markerid = e.detail.markerId
    let itemobj = this.data.markers.filter((item)=>{
        return item.id==markerid
    })
    if( itemobj.length>0 ){
      if( itemobj[0].mtype==1 ){
        wx.navigateTo({
          url: '/pages/index_youthhome_detail/index?youthid='+itemobj[0].sysid,
        })
      }else{
        wx.navigateTo({
          url: '/pages/index_active_detail/index?id='+itemobj[0].sysid,
        })
      }
    }
  },
  labeltap(e) {
    //console.log('@@@ labeltap', e)
  },
  regionchange(e){
    console.log('@@@ regionchange', e)
    const {scale, centerLocation} = e.detail
    if( e.detail.type=='end' && e.causedBy=="drag"){
      this.setData({scale,latitude:centerLocation.latitude,longitude:centerLocation.longitude})
      this.getData()
    }
  },
  anchorpointtap(e){
    console.log('@@@ anchorpointtap', e)
  }

})